package com.bing.bingPro.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * web下载Excel 工具类
 * @author qc-zhao
 */
public class WebExcelUtil {

    private WebExcelUtil() {
    }

    /**
     * 封装 EasyExcel web下载
     *
     * @param response 响应
     * @param fileName 文件名称（无需后缀）
     * @param dataList 数据集合{@link ExcelData}
     * @throws IOException -
     */
    public static void download(HttpServletResponse response, String fileName, List<ExcelData> dataList) throws IOException {

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcelFactory.write(response.getOutputStream()).build();
            for (int i = 0; i < dataList.size(); i++) {
                int l = i;
                ExcelData excelData = dataList.get(i);
                String sheetName = excelData.getSheetName();
                if (CharSequenceUtil.isBlank(sheetName)) {
                    excelData.setSheetName(String.format("sheet%d", l + 1));
                }
                ExcelWriterSheetBuilder head = EasyExcelFactory.writerSheet(i, excelData.getSheetName()).head(excelData.getClazz());
                excelWriter.write(excelData.getData(), head.build());
            }
            //千万别忘记finish 会帮忙关闭流
            if (Objects.nonNull(excelWriter)) {
                excelWriter.finish();
            }

    }

    public static void download(HttpServletResponse response, ExcelData... excelData) throws IOException {
        download(response, IdUtil.fastSimpleUUID(), excelData);
    }

    public static void download(HttpServletResponse response, String fileName, ExcelData... excelData) throws IOException {
        if (null == excelData) {
            excelData = new ExcelData[]{};
        }
        download(response, fileName, Arrays.asList(excelData));
    }

}
